<!--
 * @company : 版权所属 四川北星惯牌科技有限公司
 * @contact : 刘经理 19326416371
 -->
<template>
	<view class="box w100">
		<view class="main w100">
			<view class="head-box w100">
				<view class="nearby-head w100" :style="{paddingTop: +statusBarHeight+'px'}">
					<view class="head-info flex-row-center" @click="chooseLocationTap">
						<up-icon name="map" color="#CED0D0" size="40rpx"></up-icon>
						<text class="address" v-if="addressInfo">{{addressInfo.districtInfo}}</text>
						<text class="address" v-else>定位失败</text>
						<up-icon name="arrow-right" color="#CED0D0" size="24rpx"></up-icon>
					</view>
				</view>
				<!-- tab -->
				<view class="tab-box w100 flex-center">
					<view class="tab-content flex-center">
						<view :class="[tabIndex===index?'tab-item-active':'tab-item-in','flex-center','tab-item']"
							v-for="(item,index) in tabList" @click="changeTab(index)" :key="index">
							<text class="text">{{item.name}}</text>
						</view>
						<view :animation="animationData" class="tab-active"></view>
					</view>
				</view>
			</view>
			<cover-view class="map-box">
				<map  style="width: 100%;height: 100%;" @markertap="toTeamDetails" :latitude="positionInfo.latitude"
					:longitude="positionInfo.longitude" :markers="positionInfo.covers" :night-status="true" :scale="scale">
				</map>
			</cover-view>
		
			<view class="nearby-content" :style="{marginTop: +statusBarHeight+'px'}">
				<!-- ========门店======= -->
				<template v-if="tabIndex==0">
					<view class="nearbyStyle-one flex" v-if="itemState">
						<view class="nearby-list">
							<swiper class="swiper" @change="changePositionTwo" circular previous-margin="122rpx"
								next-margin="122rpx">
								<swiper-item v-for="(item,index) in storeInfo.list" :key="item.id">
									<view class="list_item">
										<storeItemVue :storeInfo="item"></storeItemVue>
									</view>
								</swiper-item>
							</swiper>
						</view>
					</view>
					<!-- 模板二 -->
					<view class="nearbyStyle-two flex" v-else>
						<view class="nearbyStyle-item" v-for="(item,index) in storeInfo.list" :key="item.id">
							<storeItemVue :storeInfo="item"></storeItemVue>
						</view>
					</view>
				</template>
				<!-- ========组队======= -->
				<template v-else-if="tabIndex==1">
					<view class="nearbyStyle-one flex" v-if="itemState">
						<view class="nearby-list">
							<swiper @change="changePosition" class="swiper" circular previous-margin="122rpx"
								next-margin="122rpx">
								<swiper-item v-for="(item,index) in nearbyInfo.list" :key="item.id">
									<view class="list_item">
										<nearbyItemVue :nearbyInfo="item"></nearbyItemVue>
									</view>
								</swiper-item>
							</swiper>
						</view>
					</view>
					<!-- 模板二 -->
					<view class="nearbyStyle-two flex" v-else>
						<view class="nearbyStyle-item" v-for="(item,index) in nearbyInfo.list" :key="item.t_id">
							<nearbyItemVue :nearbyInfo="item"></nearbyItemVue>
						</view>
					</view>
				</template>

			</view>
			<!-- 定位失败弹窗 -->
			<view class="positionErr-box flex-center" v-if="!addressInfo">
				<text class="text">获取当前定位失败</text>
				<view class="flex-center refsh-btn" @click="getAddressInfo">
					<up-icon name="reload" color="#2979ff" size="28rpx"></up-icon>
					<text class="btn">刷新</text>
				</view>
			</view>
			<view class="change-btn flex-center" @click="changeState">
				<up-icon name="list-dot" color="#0A534F" size="38rpx"></up-icon>
			</view>
		</view>
		<!-- 未登录导航入口 -->
		<noLoginNavVue></noLoginNavVue>
		<tabbarContentVue :current="1"></tabbarContentVue>
	</view>
</template>

<script setup>
	import nearbyStyleOne from '@/components/nearby/nearbyStyleOne.vue';
	import nearbyStyleTwo from '@/components/nearby/nearbyStyleTwo.vue';
	import tabbarContentVue from '@/components/tabbarContent/tabbarContent.vue';
	import storeItemVue from '@/components/nearby/storeItem.vue';
	import nearbyItemVue from '@/components/nearby/nearbyItem.vue';
	import noLoginNavVue from '@/components/noLoginNav/noLoginNav.vue';
	import {
		getLocationInf
	} from '@/utils/getLocation.js';
	import {
		chooseLocation
	} from '@/utils/chooseLocation';
	import {
		userInfoStore
	} from '@/stores/user';
	import {
		handleDistance,
		countDown,
		isMillisecondTimestamp
	} from '@/utils/utools.js';
	import {
		watch
	} from 'vue';
	const tabList = [{
		name: '门店'
	}, {
		name: '组队'
	}];
	const animationData = ref('');
	const userStore = userInfoStore();
	const statusBarHeight = ref(0);
	const tabIndex = ref(0);
	const scale = ref(16);
	const itemState = ref(true);
	const addressInfo = computed(() => userStore.addressInfo);
	const positionInfo = reactive({
		latitude: addressInfo.value?.latitude || 30.572924,
		longitude: addressInfo.value?.longitude || 104.066128,
		covers: [{
			id: 0,
			latitude: addressInfo.value?.latitude || 30.572924,
			longitude: addressInfo.value?.longitude || 104.066128,
			width: 36,
			height: 36,
			iconPath: '../../static/nearby/new_positioning.png'
		}]
	});
	const nearbyInfo = reactive({
		list: [],
		page: 1,
		status: 'loadmore'
	});
	const storeInfo = reactive({
		list: [],
		page: 1,
		status: 'loadmore'
	});
	onShow(() => {
		console.log('附近展示了');
	})
	const startAnimation = (type) => {
		const animation = uni.createAnimation({
			duration: 300,
		});
		animation.translateX(type).step();
		// 导出动画数据
		animationData.value = animation.export();
	};
	onLoad(async () => {
		statusBarHeight.value = uni.getSystemInfoSync().statusBarHeight;
		if (addressInfo.value) {
			getStoreList();
		}
	});
	onReachBottom(() => {
		if (tabIndex.value === 0) {
			getMoreStore();
		} else if (tabIndex.value === 1) {
			getMoreGroup();
		}
	})
	const getMoreGroup = () => { //获取更多
		if (nearbyInfo.status === 'loading' || nearbyInfo.status === 'nomore') return;
		nearbyInfo.status = 'loading';
		setTimeout(() => {
			getmainGroupList();
		}, 600)
	}
	const getmainGroupList = async (lat, lng) => { //获取组队列表
		const res = await $Api.group.getmainGroupList({
			page: nearbyInfo.page,
			type: 1,
			level: 0,
			lat: addressInfo.value?.latitude,
			lng: addressInfo.value?.longitude
		}, true)
		if (res.code === 1) {
			setTimeout(() => {}, 800)
			if (res.data.list && res.data.list.length > 0) {
				positionInfo.latitude = res.data.list[0].tlat;
				positionInfo.longitude = res.data.list[0].tlong;
				// console.log('positionInfo.latitude ', positionInfo.latitude);
				let arr = [];
				arr = res.data.list.map(val => {
					positionInfo.covers.push({
						id: val.t_id,
						latitude: val.tlat,
						longitude: val.tlong,
						width: 29,
						height: 35,
						iconPath: '../../static/nearby/positioning_icon.png'
					});
					let imageList = [];
					let fristName = '北';
					let countDownState = -1;
					if (val.juli) {
						val.juli = handleDistance(val.juli);
					}
					if (val.image) {
						if (typeof val.image === 'string') {
							imageList = val.image.split(',');
						} else if (Array.isArray(val.image)) {
							val.image.forEach(item => {
								imageList.push(item.url);
							})
						}
					};
					if (val.nickname) {
						fristName = val.nickname.charAt(0)
					}
					countDownState = computeDate(val.start_date, val.end_date)
					return {
						...val,
						imageList: imageList,
						fristName,
						countDownState
					}
				})
				nearbyInfo.list = [...nearbyInfo.list, ...arr];
			}
			if (res.data.totalPage > nearbyInfo.page) {
				nearbyInfo.status = 'loadmore';
				nearbyInfo.page++;
			} else {
				nearbyInfo.status = 'nomore';
			}
			// console.log('nearbyInfo.list', nearbyInfo.list);
		} else {
			setTimeout(() => {}, 800)
			uni.$u.toast(res.msg);
		}
	};
	const getMoreStore = () => { //获取更多
		if (storeInfo.status === 'loading' || storeInfo.status === 'nomore') return;
		storeInfo.status = 'loading';
		setTimeout(() => {
			getStoreList();
		}, 600)
	}
	const getStoreList = async () => { //获取附近门店
		const res = await $Api.store.getStoreList({
			page: storeInfo.page,
			radius: 100,
			lat: addressInfo.value?.latitude,
			lng: addressInfo.value?.longitude
		}, true)
		if (res.code === 1) {
			if (res.data.list && res.data.list.length > 0) {
				positionInfo.latitude = res.data.list[0].lat;
				positionInfo.longitude = res.data.list[0].long;
				let arr = [];
				arr = res.data.list.map(val => {
					positionInfo.covers.push({
						id: val.id,
						latitude: val.lat,
						longitude: val.long,
						width: 29,
						height: 35,
						iconPath: '../../static/nearby/positioning_icon.png'
					});
					if (val.juli) {
						val.juli = handleDistance(val.juli);
					}
					return {
						...val,
					}
				})
				arr = res.data.list;
				storeInfo.list = [...storeInfo.list, ...arr];
			}
			if (res.data.totalPage && res.data.totalPage > storeInfo.page) {
				storeInfo.status = 'loadmore';
				storeInfo.page++;
			} else {
				storeInfo.status = 'nomore';
			}
		} else {
			uni.$u.toast(res.msg);
		}
	}
	const computeDate = (startDate, endDate) => {
		if (!isMillisecondTimestamp(startDate)) { //判断毫秒级时间戳
			startDate = startDate * 1000
		}
		if (!isMillisecondTimestamp(endDate)) { //判断毫秒级时间戳
			endDate = endDate * 1000
		}
		let newDate = new Date().getTime();
		if (newDate > endDate) { //已经结束
			return -1
		} else if (newDate > startDate && newDate <= endDate) { //进行中，距结束多少时间
			return 1
		} else if (newDate <= startDate) { //未开始 距开始多少时间
			return 2
		}
	}
	const toTeamDetails = (item) => {
		if (item.detail.markerId == 0) return;
		if (tabIndex.value === 0) {
			uni.navigateTo({
				url: '/page_store/views/storeDetailsuser?storeId=' + item.detail.markerId
			})
		} else if (tabIndex.value === 1) {
			uni.navigateTo({
				url: '/page_main/views/teamDetails?id=' + item.detail.markerId
			});

		}
	}
	const changePosition = (e) => {
		let index = e.detail.current;
		let data = nearbyInfo.list[index];
		if (scale.value == 16) {
			scale.value = 15.9;
		} else {
			scale.value = 16;
		}
		positionInfo.latitude = data.tlat;
		positionInfo.longitude = data.tlong;
		if (index == (nearbyInfo.list.length - 1)) {
			getMoreGroup();
		}
	}
	const changePositionTwo = (e) => {
		let index = e.detail.current;
		let data = storeInfo.list[index];
		if (scale.value == 16) {
			scale.value = 15.9;
		} else {
			scale.value = 16;
		}
		positionInfo.latitude = data.lat;
		positionInfo.longitude = data.long;
		if (index == (storeInfo.list.length - 1)) {
			getMoreStore();
		}
	}
	const changeState = (state) => { //切换样式
		itemState.value = !itemState.value;
	}
	const changeTab = (index) => { //q切换
		tabIndex.value = index;
		if (index == 0) {
			startAnimation('0rpx');
			restStoreList();
		} else if (index == 1) {
			startAnimation('180rpx');
			restGroupList()
		}
	}
	const restGroupList = () => { //重置组队数据
		nearbyInfo.list = [];
		nearbyInfo.page = 1;
		nearbyInfo.status = 'loadmore';
		positionInfo.covers = [{
			id: 0,
			latitude: addressInfo.value.latitude,
			longitude: addressInfo.value.longitude,
			width: 36,
			height: 36,
			iconPath: '../../static/nearby/new_positioning.png'
		}];
		positionInfo.latitude = userStore.addressInfo?.latitude;
		positionInfo.longitude = userStore.addressInfo?.longitude;
		getmainGroupList()
	}
	const restStoreList = () => { //重置门店数据
		storeInfo.list = [];
		storeInfo.page = 1;
		storeInfo.status = 'loadmore';
		positionInfo.covers = [{
			id: 0,
			latitude: addressInfo.value.latitude,
			longitude: addressInfo.value.longitude,
			width: 36,
			height: 36,
			iconPath: '../../static/nearby/new_positioning.png'
		}];
		positionInfo.latitude = userStore.addressInfo?.latitude;
		positionInfo.longitude = userStore.addressInfo?.longitude;
		getStoreList();
	}
	const chooseLocationTap = async () => { //选择地理位置
		// userStore.setAddressInfo();
		const res = await chooseLocation(userStore.addressInfo?.latitude, userStore.addressInfo?.longitude);
		// console.log('chooseLocationTap', res);
		if (res.districtInfo) {
			userStore.addressInfo = res;
			if (tabIndex.value == 0) {
				restStoreList();
			} else if (tabIndex.value == 1) {
				restGroupList()
			}
		}
	}
	const getAddressInfo = async () => { //获取当前位置信息
		try {
			const res = await getLocationInf();
			if (res.latitude && res.longitude) {
				userStore.addressInfo = res;
				userStore.setUserAddress({ //给用户设置默认地区
					lat: res.latitude,
					lng: res.longitude
				});
				if (tabIndex.value == 0) {
					restStoreList();
				} else if (tabIndex.value == 1) {
					restGroupList()
				}
			}
		} catch (e) {
			console.log('getAddressInfo', e, addressInfo.value);
		}

	}
	watch(() => userStore.addressInfo, () => {
		console.log('修改了', userStore.addressInfo);
		positionInfo.covers[0] = {
			id: 0,
			latitude: addressInfo.value.latitude,
			longitude: addressInfo.value.longitude,
			width: 36,
			height: 36,
			iconPath: '../../static/nearby/new_positioning.png'
		}
	})
</script>

<style lang="scss" scoped>
	.box {
		height: 100vh;
		display: flex;
		flex-direction: column;
	}

	.main {
		flex: 1;
		position: relative;
	}

	.head-box {
		position: fixed;
		top: 0;
		left: 0;
		z-index: 9999;
	}

	.nearby-head {
		background-color: rgba(0, 0, 0, .8);
		padding: 0 48rpx;

		.head-info {
			height: 76rpx;
		}

		.address {
			max-width: 378rpx;
			font-weight: 500;
			font-size: 32rpx;
			color: #CED0D0;
			text-overflow: ellipsis;
			white-space: nowrap;
			overflow: hidden;
			margin: 0 8rpx;
		}

		.nearby-content {
			width: 100%;
			z-index: 999;
		}
	}

	.tab-box {
		margin-top: 40rpx;

		.tab-content {
			height: 68rpx;
			border-radius: 32rpx;
			background: linear-gradient(90deg, #758F98, #ADD1E2);
			position: relative;
		}

		.tab-item {
			width: 180rpx;
			height: 100%;
			border-radius: 32rpx;
			position: relative;
			z-index: 2;

			.text {
				font-size: 32rpx;
				font-weight: 600;
			}
		}

		.tab-item-active {
			// background: $btn-bg-color;
			color: $btn-text-color;
		}

		.tab-active {
			width: 180rpx;
			height: 68rpx;
			background: $btn-bg-color;
			border-radius: 32rpx;
			position: absolute;
			left: 0;
			transition: all 1s;
		}

		.tab-in {
			left: 0;
		}

		.tab-active {
			right: 0;
		}

		.tab-item-in {
			color: #0A534F;
		}
	}

	.map-box {
		width: 100vw;
		height: 100%;
		position: fixed;
		top: 0;
		left: 0;
		box-sizing: border-box;
		overflow: hidden;
		z-index: -1;
	}

	.change-btn {
		width: 66rpx;
		height: 66rpx;
		background: $attention-color;
		border-radius: 50%;
		position: fixed;
		bottom: 540rpx;
		right: 40rpx;
		z-index: 9999;
	}

	.nearbyStyle-one {
		width: 100%;
		box-sizing: border-box;
		position: absolute;
		bottom: 0;
		left: 0;
		flex-direction: column;



		.nearby-list {
			padding-bottom: 8rpx;
			height: 320rpx;

			.swiper {
				width: 100%;
				height: 100%;

				.list_item {
					width: 492rpx;
					height: 100%;
				}
			}
		}
	}

	.nearbyStyle-two {
		width: 100%;
		box-sizing: border-box;
		flex-direction: column;
		padding: 44rpx 32rpx;
		padding-top: 120rpx;
		position: relative;
		z-index: 999;

		.nearbyStyle-item {
			width: 100%;
			height: 448rpx;
			margin-bottom: 24rpx;
		}
	}

	.positionErr-box {
		flex-direction: column;
		box-sizing: border-box;
		padding: 20rpx;
		border: 1rpx solid #b3ffcc;
		width: 420rpx;
		border-radius: 12rpx;
		z-index: 999;
		position: relative;
		margin: 25vh auto;
		transform: translateY(50%);
		background-color: $page-bg-color;
		// backdrop-filter: blur(10px);
		// -webkit-backdrop-filter: blur(10px);

		.text {
			font-size: 30rpx;
			font-weight: bold;
			color: $name-color;
		}

		.refsh-btn {
			background: $btn-bg-color;
			width: 152rpx;
			height: 52rpx;
			border-radius: 26rpx;
			color: $btn-text-color;
			font-size: 28rpx;
			margin-top: 26rpx;

			.btn {
				margin-left: 8rpx;
			}
		}

	}
</style>